You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by lg...@apache.org on 2016/02/09 10:35:40 UTC
mina-sshd git commit: [SSHD-628] Take into account reported
ExitStatus on SCP download and upload
Repository: mina-sshd
Updated Branches:
refs/heads/master a3d058b09 -> dae3a5679
[SSHD-628] Take into account reported ExitStatus on SCP download and upload
Project: http://git-wip-us.apache.org/repos/asf/mina-sshd/repo
Commit: http://git-wip-us.apache.org/repos/asf/mina-sshd/commit/dae3a567
Tree: http://git-wip-us.apache.org/repos/asf/mina-sshd/tree/dae3a567
Diff: http://git-wip-us.apache.org/repos/asf/mina-sshd/diff/dae3a567
Branch: refs/heads/master
Commit: dae3a567981cf2b7db99018c90163090dbe45ece
Parents: a3d058b
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Tue Feb 9 11:35:22 2016 +0200
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Tue Feb 9 11:35:22 2016 +0200
----------------------------------------------------------------------
.../java/org/apache/sshd/client/SshClient.java | 3 +-
.../client/channel/AbstractClientChannel.java | 3 +-
.../sshd/client/channel/ClientChannel.java | 12 --
.../sshd/client/channel/ClientChannelEvent.java | 58 ++++++++
.../sshd/client/scp/AbstractScpClient.java | 74 ++++++++++-
.../sshd/client/scp/DefaultScpClient.java | 9 +-
.../common/forward/DefaultTcpipForwarder.java | 8 +-
.../apache/sshd/common/scp/ScpException.java | 57 ++++++++
.../org/apache/sshd/common/scp/ScpHelper.java | 132 ++++++++++++++++---
.../server/channel/AbstractServerChannel.java | 30 +++--
.../org/apache/sshd/server/scp/ScpCommand.java | 24 +++-
.../java/org/apache/sshd/KeepAliveTest.java | 23 ++--
.../java/org/apache/sshd/KeyReExchangeTest.java | 25 ++--
.../src/test/java/org/apache/sshd/LoadTest.java | 7 +-
.../java/org/apache/sshd/WindowAdjustTest.java | 7 +-
.../java/org/apache/sshd/client/ClientTest.java | 37 +++---
.../org/apache/sshd/client/kex/KexTest.java | 7 +-
.../org/apache/sshd/client/scp/ScpTest.java | 101 ++++++++++++++
.../java/org/apache/sshd/server/ServerTest.java | 8 +-
.../git/transport/GitSshdSessionProcess.java | 8 +-
.../apache/sshd/git/pgm/GitPgmCommandTest.java | 8 +-
21 files changed, 521 insertions(+), 120 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java b/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
index 92bfbba..5d567b1 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
@@ -65,6 +65,7 @@ import org.apache.sshd.client.auth.password.UserAuthPasswordFactory;
import org.apache.sshd.client.auth.pubkey.UserAuthPublicKeyFactory;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.config.hosts.HostConfigEntry;
import org.apache.sshd.client.config.hosts.HostConfigEntryResolver;
import org.apache.sshd.client.config.keys.ClientIdentityLoader;
@@ -1154,7 +1155,7 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open().await(); // TODO use verify and a configurable timeout
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), 0);
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
} finally {
channel.close();
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
index f3eb272..bc1642e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
@@ -203,12 +203,11 @@ public abstract class AbstractClientChannel extends AbstractChannel implements C
long t = 0;
synchronized (lock) {
for (Set<ClientChannelEvent> cond = EnumSet.noneOf(ClientChannelEvent.class);; cond.clear()) {
- if (openFuture != null && openFuture.isOpened()) {
+ if ((openFuture != null) && openFuture.isOpened()) {
cond.add(ClientChannelEvent.OPENED);
}
if (closeFuture.isClosed()) {
cond.add(ClientChannelEvent.CLOSED);
- cond.add(ClientChannelEvent.EOF);
}
if (isEofSignalled()) {
cond.add(ClientChannelEvent.EOF);
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java
index c1e968c..48bd3a0 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java
@@ -39,18 +39,6 @@ import org.apache.sshd.common.io.IoOutputStream;
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public interface ClientChannel extends Channel {
-
- enum ClientChannelEvent {
- TIMEOUT,
- CLOSED,
- STDOUT_DATA,
- STDERR_DATA,
- EOF,
- EXIT_STATUS,
- EXIT_SIGNAL,
- OPENED;
- }
-
enum Streaming {
Async,
Sync
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannelEvent.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannelEvent.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannelEvent.java
new file mode 100644
index 0000000..a0a95a6
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannelEvent.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.channel;
+
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.Set;
+
+/**
+ * Various events used by {@link ClientChannel#waitFor(java.util.Collection, long)}
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public enum ClientChannelEvent {
+ /**
+ * Timeout while waiting for other events - <B>Note:</B> meaningful only
+ * as a member of the <U>returned</U> events
+ **/
+ TIMEOUT,
+ /** Channel has been marked as closed **/
+ CLOSED,
+ /** Received STDOUT (a.k.a. channel) data **/
+ STDOUT_DATA,
+ /** Received STDERR (a.k.a. extended) data **/
+ STDERR_DATA,
+ /** Received EOF signal from remote peer **/
+ EOF,
+ /**
+ * Received exit status from remote peer
+ * @see ClientChannel#getExitStatus()
+ **/
+ EXIT_STATUS,
+ /**
+ * Received exit signal from remote peer
+ * @see ClientChannel#getExitSignal()
+ */
+ EXIT_SIGNAL,
+ /** Channel has been successfully opened */
+ OPENED;
+
+ public static final Set<ClientChannelEvent> VALUES =
+ Collections.unmodifiableSet(EnumSet.allOf(ClientChannelEvent.class));
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java b/sshd-core/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java
index c96b02c..e4f39f8 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java
@@ -32,14 +32,18 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.sshd.client.channel.ChannelExec;
+import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.PropertyResolverUtils;
import org.apache.sshd.common.SshException;
import org.apache.sshd.common.file.FileSystemFactory;
+import org.apache.sshd.common.scp.ScpException;
import org.apache.sshd.common.scp.ScpHelper;
import org.apache.sshd.common.scp.ScpTimestamp;
import org.apache.sshd.common.util.GenericUtils;
@@ -51,6 +55,9 @@ import org.apache.sshd.common.util.logging.AbstractLoggingBean;
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public abstract class AbstractScpClient extends AbstractLoggingBean implements ScpClient {
+ public static final Set<ClientChannelEvent> COMMAND_WAIT_EVENTS =
+ Collections.unmodifiableSet(EnumSet.of(ClientChannelEvent.EXIT_STATUS, ClientChannelEvent.CLOSED));
+
protected AbstractScpClient() {
super();
}
@@ -149,7 +156,10 @@ public abstract class AbstractScpClient extends AbstractLoggingBean implements S
try {
fs.close();
} catch (UnsupportedOperationException e) {
- // Ignore
+ if (log.isDebugEnabled()) {
+ log.debug("download({}) {} => {} - failed ({}) to close file system={}: {}",
+ session, remote, local, e.getClass().getSimpleName(), fs, e.getMessage());
+ }
}
}
}
@@ -231,6 +241,68 @@ public abstract class AbstractScpClient extends AbstractLoggingBean implements S
protected abstract <T> void runUpload(String remote, Collection<Option> options, Collection<T> local, AbstractScpClient.ScpOperationExecutor<T> executor) throws IOException;
+ /**
+ * Invoked by the various <code>upload/download</code> methods after having successfully
+ * completed the remote copy command and (optionally) having received an exit status
+ * from the remote server. If no exit status received within {@link FactoryManager#CHANNEL_CLOSE_TIMEOUT}
+ * the no further action is taken. Otherwise, the exit status is examined to ensure it
+ * is either OK or WARNING - if not, an {@link ScpException} is thrown
+ *
+ * @param cmd The attempted remote copy command
+ * @param channel The {@link ClientChannel} through which the command was sent - <B>Note:</B>
+ * then channel may be in the process of being closed
+ * @throws IOException If failed the command
+ * @see #handleCommandExitStatus(String, Integer)
+ */
+ protected void handleCommandExitStatus(String cmd, ClientChannel channel) throws IOException {
+ // give a chance for the exit status to be received
+ long timeout = PropertyResolverUtils.getLongProperty(channel, FactoryManager.CHANNEL_CLOSE_TIMEOUT, FactoryManager.DEFAULT_CHANNEL_CLOSE_TIMEOUT);
+ long waitStart = System.nanoTime();
+ Collection<ClientChannelEvent> events = channel.waitFor(COMMAND_WAIT_EVENTS, timeout);
+ long waitEnd = System.nanoTime();
+ if (log.isDebugEnabled()) {
+ log.debug("handleCommandExitStatus({}) cmd='{}', waited={} nanos, events={}",
+ getClientSession(), cmd, waitEnd - waitStart, events);
+ }
+
+ /*
+ * There are sometimes race conditions in the order in which channels are closed and exit-status
+ * sent by the remote peer (if at all), thus there is no guarantee that we will have an exit
+ * status here
+ */
+ handleCommandExitStatus(cmd, channel.getExitStatus());
+ }
+
+ /**
+ * Invoked by the various <code>upload/download</code> methods after having successfully
+ * completed the remote copy command and (optionally) having received an exit status
+ * from the remote server
+ *
+ * @param cmd The attempted remote copy command
+ * @param exitStatus The exit status - if {@code null} then no status was reported
+ * @throws IOException If failed the command
+ */
+ protected void handleCommandExitStatus(String cmd, Integer exitStatus) throws IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("handleCommandExitStatus({}) cmd='{}', exit-status={}", getClientSession(), cmd, ScpHelper.getExitStatusName(exitStatus));
+ }
+
+ if (exitStatus == null) {
+ return;
+ }
+
+ int statusCode = exitStatus.intValue();
+ switch (statusCode) {
+ case ScpHelper.OK: // do nothing
+ break;
+ case ScpHelper.WARNING:
+ log.warn("handleCommandExitStatus({}) cmd='{}' may have terminated with some problems", getClientSession(), cmd);
+ break;
+ default:
+ throw new ScpException("Failed to run command='" + cmd + "': " + ScpHelper.getExitStatusName(exitStatus), exitStatus);
+ }
+ }
+
protected Collection<Option> addTargetIsDirectory(Collection<Option> options) {
if (GenericUtils.isEmpty(options) || (!options.contains(Option.TargetIsDirectory))) {
// create a copy in case the original collection is un-modifiable
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/client/scp/DefaultScpClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/scp/DefaultScpClient.java b/sshd-core/src/main/java/org/apache/sshd/client/scp/DefaultScpClient.java
index 1cadea3..c3b9d02 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/scp/DefaultScpClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/scp/DefaultScpClient.java
@@ -82,6 +82,7 @@ public class DefaultScpClient extends AbstractScpClient {
// NOTE: we use a mock file system since we expect no invocations for it
ScpHelper helper = new ScpHelper(session, invOut, invIn, new MockFileSystem(remote), listener);
helper.receiveFileStream(local, ScpHelper.DEFAULT_RECEIVE_BUFFER_SIZE);
+ handleCommandExitStatus(cmd, channel);
} finally {
channel.close(false);
}
@@ -100,6 +101,7 @@ public class DefaultScpClient extends AbstractScpClient {
options.contains(Option.TargetIsDirectory),
options.contains(Option.PreserveAttributes),
ScpHelper.DEFAULT_RECEIVE_BUFFER_SIZE);
+ handleCommandExitStatus(cmd, channel);
} finally {
channel.close(false);
}
@@ -121,6 +123,7 @@ public class DefaultScpClient extends AbstractScpClient {
final Path mockPath = new MockPath(remote);
helper.sendStream(new DefaultScpStreamResolver(name, mockPath, perms, time, size, local, cmd),
time != null, ScpHelper.DEFAULT_SEND_BUFFER_SIZE);
+ handleCommandExitStatus(cmd, channel);
} finally {
channel.close(false);
}
@@ -150,9 +153,13 @@ public class DefaultScpClient extends AbstractScpClient {
try {
fs.close();
} catch (UnsupportedOperationException e) {
- // Ignore
+ if (log.isDebugEnabled()) {
+ log.debug("runUpload({}) {} => {} - failed ({}) to close file system={}: {}",
+ session, remote, local, e.getClass().getSimpleName(), fs, e.getMessage());
+ }
}
}
+ handleCommandExitStatus(cmd, channel);
} finally {
channel.close(false);
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/common/forward/DefaultTcpipForwarder.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/forward/DefaultTcpipForwarder.java b/sshd-core/src/main/java/org/apache/sshd/common/forward/DefaultTcpipForwarder.java
index 30c9b37..905a16d 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/forward/DefaultTcpipForwarder.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/forward/DefaultTcpipForwarder.java
@@ -31,7 +31,7 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.OpenFuture;
import org.apache.sshd.common.Closeable;
import org.apache.sshd.common.Factory;
@@ -80,8 +80,8 @@ public class DefaultTcpipForwarder
*/
public static final long DEFAULT_FORWARD_REQUEST_TIMEOUT = TimeUnit.SECONDS.toMillis(15L);
- public static final Set<ClientChannel.ClientChannelEvent> STATIC_IO_MSG_RECEIVED_EVENTS =
- Collections.unmodifiableSet(EnumSet.of(ClientChannel.ClientChannelEvent.OPENED, ClientChannel.ClientChannelEvent.CLOSED));
+ public static final Set<ClientChannelEvent> STATIC_IO_MSG_RECEIVED_EVENTS =
+ Collections.unmodifiableSet(EnumSet.of(ClientChannelEvent.OPENED, ClientChannelEvent.CLOSED));
private final ConnectionService service;
private final IoHandlerFactory socksProxyIoHandlerFactory = new IoHandlerFactory() {
@@ -477,7 +477,7 @@ public class DefaultTcpipForwarder
Buffer buffer = new ByteArrayBuffer(message.available() + Long.SIZE, false);
buffer.putBuffer(message);
- Collection<ClientChannel.ClientChannelEvent> result = channel.waitFor(STATIC_IO_MSG_RECEIVED_EVENTS, Long.MAX_VALUE);
+ Collection<ClientChannelEvent> result = channel.waitFor(STATIC_IO_MSG_RECEIVED_EVENTS, Long.MAX_VALUE);
if (log.isTraceEnabled()) {
log.trace("messageReceived({}) channel={}, len={} wait result: {}",
session, channel, result, buffer.array());
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpException.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpException.java b/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpException.java
new file mode 100644
index 0000000..25bcc4c
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpException.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sshd.common.scp;
+
+import java.io.IOException;
+
+import org.apache.sshd.common.util.ValidateUtils;
+
+/**
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public class ScpException extends IOException {
+ private static final long serialVersionUID = 7734851624372451732L;
+ private final Integer exitStatus;
+
+ public ScpException(String message) {
+ this(message, null);
+ }
+
+ public ScpException(Integer exitStatus) {
+ this("Exit status=" + ScpHelper.getExitStatusName(ValidateUtils.checkNotNull(exitStatus, "No exit status")), exitStatus);
+ }
+
+ public ScpException(String message, Integer exitStatus) {
+ this(message, null, exitStatus);
+ }
+
+ public ScpException(Throwable cause, Integer exitStatus) {
+ this(ValidateUtils.checkNotNull(cause, "No cause").getMessage(), cause, exitStatus);
+ }
+
+ public ScpException(String message, Throwable cause, Integer exitStatus) {
+ super(message, cause);
+ this.exitStatus = exitStatus;
+ }
+
+ public Integer getExitStatus() {
+ return exitStatus;
+ }
+}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java b/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java
index d865f01..9a0f806 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/scp/ScpHelper.java
@@ -388,7 +388,12 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
resolver.postProcessReceivedData(name, preserve, perms, time);
ack();
- readAck(false);
+
+ int replyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ log.debug("receiveStream({})[{}] ack reply code={}", this, resolver, replyCode);
+ }
+ validateAckReplyCode("receiveStream", resolver, replyCode, false);
}
protected void updateFileProperties(Path file, Set<PosixFilePermission> perms, ScpTimestamp time) throws IOException {
@@ -431,7 +436,11 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
}
public void send(Collection<String> paths, boolean recursive, boolean preserve, int bufferSize) throws IOException {
- readAck(false);
+ int readyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ log.debug("send({}) ready code={}", paths, readyCode);
+ }
+ validateOperationReadyCode("send", "Paths", readyCode, false);
LinkOption[] options = IoUtils.getLinkOptions(false);
for (String pattern : paths) {
@@ -475,7 +484,11 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
}
public void sendPaths(Collection<? extends Path> paths, boolean recursive, boolean preserve, int bufferSize) throws IOException {
- readAck(false);
+ int readyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ log.debug("sendPaths({}) ready code={}", paths, readyCode);
+ }
+ validateOperationReadyCode("sendPaths", "Paths", readyCode, false);
LinkOption[] options = IoUtils.getLinkOptions(false);
for (Path file : paths) {
@@ -569,27 +582,38 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
if (preserve && (time != null)) {
String cmd = "T" + TimeUnit.MILLISECONDS.toSeconds(time.getLastModifiedTime())
+ " " + "0" + " " + TimeUnit.MILLISECONDS.toSeconds(time.getLastAccessTime())
- + " " + "0" + "\n";
+ + " " + "0";
if (log.isDebugEnabled()) {
- log.debug("sendStream({})[{}] send timestamp={} command: {}",
- this, resolver, time, cmd.substring(0, cmd.length() - 1));
+ log.debug("sendStream({})[{}] send timestamp={} command: {}", this, resolver, time, cmd);
}
out.write(cmd.getBytes(StandardCharsets.UTF_8));
+ out.write('\n');
out.flush();
- readAck(false);
+
+ int readyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ log.debug("sendStream({})[{}] command='{}' ready code={}", this, resolver, cmd, readyCode);
+ }
+ validateAckReplyCode(cmd, resolver, readyCode, false);
}
Set<PosixFilePermission> perms = EnumSet.copyOf(resolver.getPermissions());
String octalPerms = preserve ? getOctalPermissions(perms) : "0644";
String fileName = resolver.getFileName();
- String cmd = "C" + octalPerms + " " + fileSize + " " + fileName + "\n";
+ String cmd = "C" + octalPerms + " " + fileSize + " " + fileName;
if (log.isDebugEnabled()) {
- log.debug("sendStream({})[{}] send 'C' command: {}",
- this, resolver, cmd.substring(0, cmd.length() - 1));
+ log.debug("sendStream({})[{}] send 'C' command: {}", this, resolver, cmd);
}
out.write(cmd.getBytes(StandardCharsets.UTF_8));
+ out.write('\n');
out.flush();
- readAck(false);
+
+ int readyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ log.debug("sendStream({})[{}] command='{}' ready code={}",
+ this, resolver, cmd.substring(0, cmd.length() - 1), readyCode);
+ }
+ validateAckReplyCode(cmd, resolver, readyCode, false);
try (InputStream in = resolver.resolveSourceStream()) {
Path path = resolver.getEventListenerFilePath();
@@ -603,7 +627,36 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
}
}
ack();
- readAck(false);
+
+ readyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ log.debug("sendStream({})[{}] command='{}' reply code={}", this, resolver, cmd, readyCode);
+ }
+ validateAckReplyCode("sendStream", resolver, readyCode, false);
+ }
+
+ protected void validateOperationReadyCode(String command, Object location, int readyCode, boolean eofAllowed) throws IOException {
+ validateCommandStatusCode(command, location, readyCode, eofAllowed);
+ }
+
+ protected void validateAckReplyCode(String command, Object location, int replyCode, boolean eofAllowed) throws IOException {
+ validateCommandStatusCode(command, location, replyCode, eofAllowed);
+ }
+
+ protected void validateCommandStatusCode(String command, Object location, int statusCode, boolean eofAllowed) throws IOException {
+ switch (statusCode) {
+ case -1:
+ if (!eofAllowed) {
+ throw new EOFException("Unexpected EOF for command='" + command + "' on " + location);
+ }
+ break;
+ case OK:
+ break;
+ case WARNING:
+ break;
+ default:
+ throw new ScpException("Bad reply code (" + statusCode + ") for command='" + command + "' on " + location, Integer.valueOf(statusCode));
+ }
}
public void sendDir(Path local, boolean preserve, int bufferSize) throws IOException {
@@ -619,28 +672,42 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
FileTime lastAccess = basic.lastAccessTime();
String cmd = "T" + lastModified.to(TimeUnit.SECONDS) + " "
+ "0" + " " + lastAccess.to(TimeUnit.SECONDS) + " "
- + "0" + "\n";
+ + "0";
if (log.isDebugEnabled()) {
log.debug("sendDir({})[{}] send last-modified={}, last-access={} command: {}",
- this, path, lastModified, lastAccess, cmd.substring(0, cmd.length() - 1));
+ this, path, lastModified, lastAccess, cmd);
}
out.write(cmd.getBytes(StandardCharsets.UTF_8));
+ out.write('\n');
out.flush();
- readAck(false);
+
+ int readyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ if (log.isDebugEnabled()) {
+ log.debug("sendDir({})[{}] command='{}' ready code={}", this, path, cmd, readyCode);
+ }
+ }
+ validateAckReplyCode(cmd, path, readyCode, false);
}
LinkOption[] options = IoUtils.getLinkOptions(false);
Set<PosixFilePermission> perms = IoUtils.getPermissions(path, options);
String cmd = "D" + (preserve ? getOctalPermissions(perms) : "0755") + " "
- + "0" + " " + path.getFileName().toString() + "\n";
+ + "0" + " " + path.getFileName().toString();
if (log.isDebugEnabled()) {
- log.debug("sendDir({})[{}] send 'D' command: {}",
- this, path, cmd.substring(0, cmd.length() - 1));
+ log.debug("sendDir({})[{}] send 'D' command: {}", this, path, cmd);
}
out.write(cmd.getBytes(StandardCharsets.UTF_8));
+ out.write('\n');
out.flush();
- readAck(false);
+
+ int readyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ log.debug("sendDir({})[{}] command='{}' ready code={}",
+ this, path, cmd.substring(0, cmd.length() - 1), readyCode);
+ }
+ validateAckReplyCode(cmd, path, readyCode, false);
try (DirectoryStream<Path> children = Files.newDirectoryStream(path)) {
listener.startFolderEvent(FileOperation.SEND, path, perms);
@@ -666,7 +733,13 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
}
out.write("E\n".getBytes(StandardCharsets.UTF_8));
out.flush();
- readAck(false);
+
+
+ readyCode = readAck(false);
+ if (log.isDebugEnabled()) {
+ log.debug("sendDir({})[{}] 'E' command reply code=", this, path, readyCode);
+ }
+ validateAckReplyCode("E", path, readyCode, false);
}
public static String getOctalPermissions(Path path, LinkOption... options) throws IOException {
@@ -780,6 +853,23 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
return out;
}
+ public static String getExitStatusName(Integer exitStatus) {
+ if (exitStatus == null) {
+ return "null";
+ }
+
+ switch (exitStatus.intValue()) {
+ case OK:
+ return "OK";
+ case WARNING:
+ return "WARNING";
+ case ERROR:
+ return "ERROR";
+ default:
+ return exitStatus.toString();
+ }
+ }
+
public void ack() throws IOException {
out.write(0);
out.flush();
@@ -818,7 +908,7 @@ public class ScpHelper extends AbstractLoggingBean implements SessionHolder<Sess
if (log.isDebugEnabled()) {
log.debug("readAck({})[EOF={}] received error: {}", this, canEof, line);
}
- throw new IOException("Received nack: " + line);
+ throw new ScpException("Received nack: " + line, Integer.valueOf(c));
}
default:
break;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java b/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java
index 3edb2b5..e24ba9b 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java
@@ -19,6 +19,7 @@
package org.apache.sshd.server.channel;
import java.io.IOException;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.sshd.client.future.DefaultOpenFuture;
import org.apache.sshd.client.future.OpenFuture;
@@ -40,7 +41,7 @@ import org.apache.sshd.server.session.ServerSession;
*/
public abstract class AbstractServerChannel extends AbstractChannel implements ServerChannel {
- protected boolean exitStatusSent;
+ protected final AtomicBoolean exitStatusSent = new AtomicBoolean(false);
protected AbstractServerChannel() {
this("");
@@ -110,20 +111,25 @@ public abstract class AbstractServerChannel extends AbstractChannel implements S
}
protected void sendExitStatus(int v) throws IOException {
- if (!exitStatusSent) {
- exitStatusSent = true;
+ if (exitStatusSent.getAndSet(true)) {
if (log.isDebugEnabled()) {
- log.debug("sendExitStatus({}) SSH_MSG_CHANNEL_REQUEST exit-status={}", this, v);
+ log.debug("sendExitStatus({}) exit-status={} - already sent", this, v);
}
+ notifyStateChanged(); // just in case
+ return;
+ }
- Session session = getSession();
- Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_REQUEST, Long.SIZE);
- buffer.putInt(getRecipient());
- buffer.putString("exit-status");
- buffer.putBoolean(false); // want-reply - must be FALSE - see https://tools.ietf.org/html/rfc4254 section 6.10
- buffer.putInt(v);
- writePacket(buffer);
- notifyStateChanged();
+ if (log.isDebugEnabled()) {
+ log.debug("sendExitStatus({}) SSH_MSG_CHANNEL_REQUEST exit-status={}", this, v);
}
+
+ Session session = getSession();
+ Buffer buffer = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_REQUEST, Long.SIZE);
+ buffer.putInt(getRecipient());
+ buffer.putString("exit-status");
+ buffer.putBoolean(false); // want-reply - must be FALSE - see https://tools.ietf.org/html/rfc4254 section 6.10
+ buffer.putInt(v);
+ writePacket(buffer);
+ notifyStateChanged();
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/main/java/org/apache/sshd/server/scp/ScpCommand.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/scp/ScpCommand.java b/sshd-core/src/main/java/org/apache/sshd/server/scp/ScpCommand.java
index e5b222b..2a48a9a 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/scp/ScpCommand.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/scp/ScpCommand.java
@@ -28,6 +28,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import org.apache.sshd.common.file.FileSystemAware;
+import org.apache.sshd.common.scp.ScpException;
import org.apache.sshd.common.scp.ScpHelper;
import org.apache.sshd.common.scp.ScpTransferEventListener;
import org.apache.sshd.common.util.GenericUtils;
@@ -263,9 +264,20 @@ public class ScpCommand
} catch (IOException e) {
ServerSession session = getServerSession();
try {
- exitValue = ScpHelper.ERROR;
+ Integer statusCode = null;
+ if (e instanceof ScpException) {
+ statusCode = ((ScpException) e).getExitStatus();
+ }
+ exitValue = (statusCode == null) ? ScpHelper.ERROR : statusCode.intValue();
+ // this is an exception so status cannot be OK/WARNING
+ if ((exitValue == ScpHelper.OK) || (exitValue == ScpHelper.WARNING)) {
+ if (log.isDebugEnabled()) {
+ log.debug("run({})[{}] normalize status code={}", session, name, exitValue);
+ }
+ exitValue = ScpHelper.ERROR;
+ }
exitMessage = GenericUtils.trimToEmpty(e.getMessage());
- ScpHelper.sendResponseMessage(out, exitValue, exitMessage);
+ writeCommandResponseMessage(name, exitValue, exitMessage);
} catch (IOException e2) {
if (log.isDebugEnabled()) {
log.debug("run({})[{}] Failed ({}) to send error response: {}",
@@ -290,6 +302,14 @@ public class ScpCommand
}
}
+ protected void writeCommandResponseMessage(String command, int exitValue, String exitMessage) throws IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("writeCommandResponseMessage({}) command='{}', exit-status={}: {}",
+ getServerSession(), command, exitValue, exitMessage);
+ }
+ ScpHelper.sendResponseMessage(out, exitValue, exitMessage);
+ }
+
@Override
public String toString() {
return name;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java b/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java
index aeb5b61..149fecc 100644
--- a/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java
@@ -27,6 +27,7 @@ import java.util.concurrent.TimeUnit;
import org.apache.sshd.client.ClientFactoryManager;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.PropertyResolverUtils;
@@ -83,11 +84,9 @@ public class KeepAliveTest extends BaseTestSupport {
session.auth().verify(5L, TimeUnit.SECONDS);
try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), WAIT);
- assertTrue("Wrong channel state: " + result,
- result.containsAll(
- EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED, ClientChannel.ClientChannelEvent.EOF)));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
+ assertTrue("Wrong channel state: " + result, result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)));
}
} finally {
client.stop();
@@ -105,9 +104,9 @@ public class KeepAliveTest extends BaseTestSupport {
session.auth().verify(5L, TimeUnit.SECONDS);
try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), WAIT);
- assertTrue("Wrong channel state: " + result, result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
+ assertTrue("Wrong channel state: " + result, result.contains(ClientChannelEvent.TIMEOUT));
}
} finally {
client.stop();
@@ -134,13 +133,11 @@ public class KeepAliveTest extends BaseTestSupport {
channel.open().verify(9L, TimeUnit.SECONDS);
assertTrue("Latch time out", TestEchoShell.latch.await(10L, TimeUnit.SECONDS));
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), WAIT);
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
assertTrue("Wrong channel state: " + result,
result.containsAll(
- EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED,
- ClientChannel.ClientChannelEvent.EOF,
- ClientChannel.ClientChannelEvent.OPENED)));
+ EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.OPENED)));
}
} finally {
TestEchoShell.latch = null;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
index 2be7c80..5670612 100644
--- a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
@@ -39,6 +39,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.NamedFactory;
@@ -314,9 +315,9 @@ public class KeyReExchangeTest extends BaseTestSupport {
teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
teeOut.flush();
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
byte[] expected = sent.toByteArray();
if (!pipedCount.tryAcquire(expected.length, 13L, TimeUnit.SECONDS)) {
@@ -428,9 +429,9 @@ public class KeyReExchangeTest extends BaseTestSupport {
teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
teeOut.flush();
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
sentData = sent.toByteArray();
if (!pipedCount.tryAcquire(sentData.length, 13L, TimeUnit.SECONDS)) {
@@ -562,9 +563,9 @@ public class KeyReExchangeTest extends BaseTestSupport {
teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
teeOut.flush();
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
sentData = sent.toByteArray();
if (!pipedCount.tryAcquire(sentData.length, 13L, TimeUnit.SECONDS)) {
@@ -692,9 +693,9 @@ public class KeyReExchangeTest extends BaseTestSupport {
teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
teeOut.flush();
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
sentData = sent.toByteArray();
if (!pipedCount.tryAcquire(sentData.length, 13L, TimeUnit.SECONDS)) {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
index 63272bd..9916d14 100644
--- a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
@@ -32,6 +32,7 @@ import java.util.concurrent.TimeUnit;
import org.apache.sshd.client.ClientBuilder;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.PropertyResolverUtils;
@@ -145,9 +146,9 @@ public class LoadTest extends BaseTestSupport {
pipedIn.flush();
}
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
} finally {
channel.close(false);
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java b/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java
index 0380e56..f7017b3 100644
--- a/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java
@@ -35,6 +35,7 @@ import java.util.concurrent.atomic.AtomicReference;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.Factory;
import org.apache.sshd.common.future.SshFutureListener;
@@ -124,9 +125,9 @@ public class WindowAdjustTest extends BaseTestSupport {
channel.setErr(new NoCloseOutputStream(System.err));
channel.open().verify(15L, TimeUnit.SECONDS);
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(2L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(2L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
}
} finally {
client.stop();
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
index cbd924c..24b47cb 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
@@ -57,6 +57,7 @@ import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.channel.ChannelSubsystem;
import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.OpenFuture;
import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
@@ -578,9 +579,9 @@ public class ClientTest extends BaseTestSupport {
}
});
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
assertEquals("Mismatched sent and received data size", nbMessages * message.length, baosOut.size());
}
@@ -615,9 +616,9 @@ public class ClientTest extends BaseTestSupport {
// That's ok, the channel is being closed by the other side
}
- Collection<ClientChannel.ClientChannelEvent> mask = EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED);
- Collection<ClientChannel.ClientChannelEvent> result = channel.waitFor(mask, TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> mask = EnumSet.of(ClientChannelEvent.CLOSED);
+ Collection<ClientChannelEvent> result = channel.waitFor(mask, TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
assertTrue("Missing close event: " + result, result.containsAll(mask));
assertTrue("Failed to close session on time", session.close(false).await(7L, TimeUnit.SECONDS));
} finally {
@@ -660,9 +661,9 @@ public class ClientTest extends BaseTestSupport {
teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
teeOut.flush();
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting on channel close", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting on channel close", result.contains(ClientChannelEvent.TIMEOUT));
channel.close(false);
client.stop();
@@ -705,9 +706,9 @@ public class ClientTest extends BaseTestSupport {
pipedIn.flush();
}
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting on channel close", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting on channel close", result.contains(ClientChannelEvent.TIMEOUT));
channel.close(false);
client.stop();
@@ -771,9 +772,9 @@ public class ClientTest extends BaseTestSupport {
teeOut.write(sb.toString().getBytes(StandardCharsets.UTF_8));
}
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting on channel close", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting on channel close", result.contains(ClientChannelEvent.TIMEOUT));
channel.close(false);
client.stop();
@@ -828,9 +829,9 @@ public class ClientTest extends BaseTestSupport {
outputDebugMessage("Sent %d Kb in %d ms", bytes / 1024, t1 - t0);
outputDebugMessage("Waiting for channel to be closed");
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(35L));
- assertFalse("Timeout while waiting on channel close", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(35L));
+ assertFalse("Timeout while waiting on channel close", result.contains(ClientChannelEvent.TIMEOUT));
channel.close(false);
client.stop();
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java b/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java
index e7c7b7a..f6ccfbd 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java
@@ -32,6 +32,7 @@ import java.util.concurrent.TimeUnit;
import org.apache.sshd.client.ClientBuilder;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.channel.Channel;
@@ -134,9 +135,9 @@ public class KexTest extends BaseTestSupport {
teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
teeOut.flush();
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
- assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
+ assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
}
} finally {
client.stop();
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java b/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java
index 9c90e29..57d49ba 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java
@@ -34,6 +34,7 @@ import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.Set;
+import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.sshd.client.SshClient;
@@ -43,12 +44,17 @@ import org.apache.sshd.common.channel.Channel;
import org.apache.sshd.common.file.FileSystemFactory;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.common.random.Random;
+import org.apache.sshd.common.scp.ScpException;
import org.apache.sshd.common.scp.ScpHelper;
import org.apache.sshd.common.scp.ScpTransferEventListener;
import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.OsUtils;
+import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.common.util.io.IoUtils;
+import org.apache.sshd.server.Command;
+import org.apache.sshd.server.ExitCallback;
import org.apache.sshd.server.SshServer;
+import org.apache.sshd.server.scp.ScpCommand;
import org.apache.sshd.server.scp.ScpCommandFactory;
import org.apache.sshd.util.test.BaseTestSupport;
import org.apache.sshd.util.test.JSchLogger;
@@ -685,6 +691,101 @@ public class ScpTest extends BaseTestSupport {
}
}
+ @Test // see SSHD-628
+ public void testScpExitStatusPropagation() throws Exception {
+ final int TEST_EXIT_VALUE = 7365;
+ class InternalScpCommand extends ScpCommand implements ExitCallback {
+ private ExitCallback delegate;
+
+ public InternalScpCommand(String command, ExecutorService executorService, boolean shutdownOnExit,
+ int sendSize, int receiveSize, ScpTransferEventListener eventListener) {
+ super(command, executorService, shutdownOnExit, sendSize, receiveSize, eventListener);
+ }
+
+ @Override
+ protected void writeCommandResponseMessage(String command, int exitValue, String exitMessage) throws IOException {
+ outputDebugMessage("writeCommandResponseMessage(%s) status=%d", command, exitValue);
+ super.writeCommandResponseMessage(command, TEST_EXIT_VALUE, exitMessage);
+ }
+
+ @Override
+ public void setExitCallback(ExitCallback callback) {
+ delegate = callback;
+ super.setExitCallback(this);
+ }
+
+ @Override
+ public void onExit(int exitValue) {
+ onExit(exitValue, Integer.toString(exitValue));
+ }
+
+ @Override
+ public void onExit(int exitValue, String exitMessage) {
+ outputDebugMessage("onExit(%s) status=%d", this, exitValue);
+ if (exitValue == ScpHelper.OK) {
+ delegate.onExit(TEST_EXIT_VALUE, exitMessage);
+ } else {
+ delegate.onExit(exitValue, exitMessage);
+ }
+ }
+ }
+ sshd.setCommandFactory(new ScpCommandFactory() {
+ @Override
+ public Command createCommand(String command) {
+ ValidateUtils.checkTrue(command.startsWith(ScpHelper.SCP_COMMAND_PREFIX), "Bad SCP command: %s", command);
+ return new InternalScpCommand(command, getExecutorService(), isShutdownOnExit(), getSendBufferSize(), getReceiveBufferSize(), ScpTransferEventListener.EMPTY);
+ }
+ });
+
+ try (SshClient client = setupTestClient()) {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = session.createScpClient();
+ Path targetPath = detectTargetFolder();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, ScpHelper.SCP_COMMAND_PREFIX, getClass().getSimpleName(), getCurrentTestName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ Path remoteFile = remoteDir.resolve("file.txt");
+ String remotePath = Utils.resolveRelativeRemotePath(parentPath, remoteFile);
+ byte[] data = (getClass().getName() + "#" + getCurrentTestName()).getBytes(StandardCharsets.UTF_8);
+ outputDebugMessage("Upload data to %s", remotePath);
+ try {
+ scp.upload(data, remotePath, EnumSet.allOf(PosixFilePermission.class), null);
+ outputDebugMessage("Upload success to %s", remotePath);
+ } catch(ScpException e) {
+ Integer exitCode = e.getExitStatus();
+ assertNotNull("No upload exit status", exitCode);
+ assertEquals("Mismatched upload exit status", TEST_EXIT_VALUE, exitCode.intValue());
+ }
+
+ if (Files.deleteIfExists(remoteFile)) {
+ outputDebugMessage("Deleted remote file %s", remoteFile);
+ }
+
+ try (OutputStream out = Files.newOutputStream(remoteFile)) {
+ out.write(data);
+ }
+
+ try {
+ byte[] downloaded = scp.downloadBytes(remotePath);
+ outputDebugMessage("Download success to %s: %s", remotePath, new String(downloaded, StandardCharsets.UTF_8));
+ } catch(ScpException e) {
+ Integer exitCode = e.getExitStatus();
+ assertNotNull("No download exit status", exitCode);
+ assertEquals("Mismatched download exit status", TEST_EXIT_VALUE, exitCode.intValue());
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
// see http://stackoverflow.com/questions/2717936/file-createnewfile-creates-files-with-last-modified-time-before-actual-creatio
// See https://msdn.microsoft.com/en-us/library/ms724290(VS.85).aspx
private static void assertLastModifiedTimeEquals(File file, boolean modSuccess, long expectedSeconds) {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
index 98a97dc..05dfd44 100644
--- a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
@@ -44,7 +44,7 @@ import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.auth.keyboard.UserInteraction;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ChannelShell;
-import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.session.ClientConnectionServiceFactory;
import org.apache.sshd.client.session.ClientSession;
@@ -616,9 +616,9 @@ public class ServerTest extends BaseTestSupport {
assertTrue("No changes in open channels", channelListener.waitForModification(3L, TimeUnit.SECONDS));
assertTrue("No open server side channels", GenericUtils.size(channelListener.getOpenChannels()) > 0);
- Collection<ClientChannel.ClientChannelEvent> result =
- shell.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(17L));
- assertFalse("Channel close timeout", result.contains(ClientChannel.ClientChannelEvent.TIMEOUT));
+ Collection<ClientChannelEvent> result =
+ shell.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(17L));
+ assertFalse("Channel close timeout", result.contains(ClientChannelEvent.TIMEOUT));
Integer status = shell.getExitStatus();
assertNotNull("No exit status", status);
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionProcess.java
----------------------------------------------------------------------
diff --git a/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionProcess.java b/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionProcess.java
index a96b5f3..576712c 100644
--- a/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionProcess.java
+++ b/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionProcess.java
@@ -26,7 +26,7 @@ import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
import org.apache.sshd.client.channel.ChannelExec;
-import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.common.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -64,13 +64,13 @@ public class GitSshdSessionProcess extends Process {
@Override // TODO in Java-8 implement also waitFor(long, TimeUnit)
public int waitFor() throws InterruptedException {
- Collection<ClientChannel.ClientChannelEvent> res =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), waitTimeout);
+ Collection<ClientChannelEvent> res =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), waitTimeout);
if (log.isTraceEnabled()) {
log.trace("waitFor({}) channel={}, timeout={} millis.: {}",
commandName, channel, waitTimeout, res);
}
- if (res.contains(ClientChannel.ClientChannelEvent.CLOSED)) {
+ if (res.contains(ClientChannelEvent.CLOSED)) {
return 0;
} else {
return -1;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/dae3a567/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java
----------------------------------------------------------------------
diff --git a/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java b/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java
index 33e6f61..a6be166 100644
--- a/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java
+++ b/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java
@@ -27,7 +27,7 @@ import java.util.concurrent.TimeUnit;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelExec;
-import org.apache.sshd.client.channel.ClientChannel;
+import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.util.net.SshdSocketAddress;
@@ -100,9 +100,9 @@ public class GitPgmCommandTest extends BaseTestSupport {
channel.setErr(System.err);
channel.open().verify(11L, TimeUnit.SECONDS);
- Collection<ClientChannel.ClientChannelEvent> result =
- channel.waitFor(EnumSet.of(ClientChannel.ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(1L));
- assertTrue("Command '" + command + "'not completed on time: " + result, result.contains(ClientChannel.ClientChannelEvent.CLOSED));
+ Collection<ClientChannelEvent> result =
+ channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(1L));
+ assertTrue("Command '" + command + "'not completed on time: " + result, result.contains(ClientChannelEvent.CLOSED));
Integer status = channel.getExitStatus();
if (status != null) {